<?php

namespace app\web\controller;

use app\common\controller\Smscm;
use app\common\helper\FormatHelper;
use app\common\model\Discount;
use app\common\model\HandCard;
use app\common\model\HandCard as HandCardM;
use app\common\service\CommonService;
use app\common\service\PrintService;
use app\common\service\RoomCheckOutService;
use app\common\service\RoomCostService;
use app\common\service\SendVoiceMsgService;
use think\Db;
use app\common\service\FeiEPrintService;
use app\common\model\Room as RoomModel;
use Carbon\Carbon;
use think\Exception;


/**
 * 房间结账控制器
 * @package app\index\controller
 */
class RoomCheckOut extends Auth
{
    public $noNeedLogin = [];


    /**
     * 获取用户房间结账列表
     */
    public function check_out()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $margeRoomData = '';
            $margeHandCardData = '';
            //房间ID合并
            if(isset($getData['room_id']) && !empty($getData['room_id'])){
                $margeRoomData = Db::name('qt_room')->where('id', $getData['room_id'])->value('marge');
            }
            //手牌号合并
            if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                $margeHandCardData = Db::name('qt_hand_grant')
                    ->alias('grant')
                    ->leftJoin('qt_hand_card card','card.id = grant.hand_card_id')
                    ->where(['card.name'=>$getData['hand_card_name'],'grant.status'=>'2','grant.store_id'=>$this->userInfo['store_id']])
                    ->value('marge');
            }
            //房间号合并
            if(isset($getData['room_name']) && !empty($getData['room_name'])){
                $roomId = Db::name('qt_room')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['room_name']])->value('id');
                $margeRoomData = Db::name('qt_room')->where('id', $roomId)->value('marge');
            }
            if (!empty($margeRoomData) || !empty($margeHandCardData)) {
                //有合并房间
                if($margeRoomData != ''){
                    $margeRoomID = explode(',', $margeRoomData);
                }else{
                    $margeRoomID = null;
                }
                if($margeHandCardData != ''){
                    $margeHandCard = explode(',', $margeHandCardData);
                    $handCardId = Db::name('qt_hand_grant')->whereIn('id',$margeHandCard)->column('hand_card_id');
                    $margeHandCard = $handCardId;
                }else{
                    $margeHandCard = null;
                }
                $sql =   Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,room_id,hand_card_id,order_id')
                    ->whereNotNull('engineer_id')
                    ->where('is_delete',2)
                    ->where('engineer_id','neq','0')
                    ->where(['is_change'=>'1','pay_status'=>'0']);
                if($margeRoomID != null ){
                    $sql->whereIn('room_id',$margeRoomID);
                }
                if($margeHandCard != null){
                    $sql->whereIn('hand_card_id',$margeHandCard);
                }
                $projectRes = $sql->select();
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['type'] = 'project';
                    $projectRes[$key]['order_id'] = $value['order_id'];
                    $projectRes[$key]['activity_price'] = $value['price'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                    $projectRes[$key]['number'] =1;
                }

                if($margeRoomID != null){
                    //插入房费
                    foreach ($margeRoomID as $k => $room_id) {
                        $room_data = Db::name('qt_room')->where('id', $room_id)->find();
                        RoomCostService::saveCostOrder($room_data['store_id'], $room_id, $this->userInfo);
                    }
                }
                $goodsSql = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,hand_card_id,old_card_id,goods_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,order_id,sale_id,business_type,room_id')
                    ->where('pay_status', '0')
                    ->where(['status'=>'1']);
                if($margeRoomID != null){
                    $goodsSql->whereIn('room_id',$margeRoomID);
                }
                if($margeHandCard != null){
                    $goodsSql->whereIn('hand_card_id',$margeHandCard);
                }
                $productRes = $goodsSql->select();
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['type'] = 'goods';
                    $productRes[$key]['project_id'] =$value['goods_id'];
                    $productRes[$key]['activity_price'] = $value['goods_price'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');
                    $productRes[$key]['room_name'] = Db::name('qt_room')->where('id',$value['room_id'])->value('name');
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                    $productRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                    $productRes[$key]['old_hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                }
                $packageOriginal = array_merge($projectRes,$productRes);
                //dump($packageOriginal);

                $packageProjectData = [];
                $packageGoodsData = [];
                foreach ($packageOriginal as $key=>$value){
                    if($value['type'] == 'project'){
                        if (isset($packageProjectData[$value['project_id']])) {

                            $packageProjectData[$value['project_id']]['number'] += 1;
                        }else {
                            $packageProjectData[$value['project_id']] = $value;
                            $packageProjectData[$value['project_id']]['number'] = 1;
                        }
                    }elseif($value['type'] == 'goods'){
                        if (isset($packageGoodsData[$value['goods_id']])) {

                            $packageGoodsData[$value['goods_id']]['number'] += $value['goods_num'];
                        }else {
                            $packageGoodsData[$value['goods_id']] = $value;
                            $packageGoodsData[$value['goods_id']]['number'] = $value['goods_num'];
                        }
                    }
                }
                $packageOriginalData = array_merge($packageGoodsData,$packageProjectData);

                $packageSql = Db::name('qt_data_package')
                    ->field('id,name,price')
                    ->where(['store_id'=>$this->userInfo['store_id']])
                    ->select();
                foreach ($packageSql as $key=>$value){
                    $packageSql[$key]['list'] = Db::name('qt_data_package_item')
                        ->field('id,package_id,item_id as project_id,item_type as type,number')
                        ->where(['package_id'=>$value['id']])
                        ->select();
                }

                $packageSql = CommonService::useTaoCan($packageSql,$packageOriginalData);
                $data['package'] = $packageSql;
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $data['project_new'] = CommonService::decGoodsData($projectRes,$packageSql,'project');
                $data['project_new'] = array_values($data['project_new']);
                $data['goods_new'] = CommonService::decGoodsData($productRes,$packageSql,'goods');
                $data['goods_new'] = array_values($data['goods_new']);
                $this->result('请求成功', $data, 200);
            } else {
                $where = false;
                //单个房间项目
                $sql = Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,order_id,room_id,hand_card_id')
                    ->where('is_change', '1')
                    ->where('pay_status', '0')
                    ->where('is_delete', 2)
                    ->whereNotNull('engineer_id')
                    ->where('engineer_id','neq','0');
                //房间号筛选
                if(isset($getData['room_id']) && !empty($getData['room_id'])){
                    $sql->where('room_id',$getData['room_id']);
                    $where = true;
                }
                //房间号筛选
                if(isset($getData['room_name']) && !empty($getData['room_name'])){
                    $roomId = Db::name('qt_room')->where(['name'=>$getData['room_name'],'store_id'=>$this->userInfo['store_id']])->value('id');
                    if($roomId != null){
                        $where = true;
                    }
                    $sql->where('room_id',$roomId);
                }
                //手牌筛选
                if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                    $handCardId = Db::name('qt_hand_card')
                        ->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])
                        ->find();
                    if($handCardId != null){
                        $where = true;
                    }
                    $sql->where('hand_card_id',$handCardId['id']);
                }

                //技师号筛选
                if(isset($getData['work_number']) && !empty($getData['work_number'])){
                    $engineerId = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_number'=>$getData['work_number']])->value('id');
                    if($engineerId != null){
                        $where = true;
                    }
                    $sql->where('engineer_id',$engineerId);
                }
                if($where == true){
                    $projectRes = $sql->select();
                }else{
                    $projectRes = [];
                }
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['type'] = 'project';
                    $projectRes[$key]['activity_price'] = $value['price'];
                    $projectRes[$key]['order_id'] = $value['order_id'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                }
                //插入房费
                $room_data = Db::name('qt_room')->where('id', $getData['room_id'])->find();
                RoomCostService::saveCostOrder($room_data['store_id'], $getData['room_id'], $this->userInfo);
                //商品
                $goodsWhere = false;
                $goodsSql = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,goods_id,room_id,hand_card_id,old_card_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,business_type,order_id,sale_id')
                    ->where('pay_status', '0')
                    ->where(['status'=>'1']);
                //房间号筛选
                if(isset($getData['room_id']) && !empty($getData['room_id'])){
                    $goodsSql->where('room_id',$getData['room_id']);
                    $goodsWhere = true;
                }
                //房间号筛选
                if(isset($getData['room_name']) && !empty($getData['room_name'])){
                    $roomId = Db::name('qt_room')->where(['name'=>$getData['room_name'],'store_id'=>$this->userInfo['store_id']])->value('id');
                    if($roomId != null){
                        $goodsWhere = true;
                    }
                    $goodsSql->where('room_id',$roomId);

                }
                //手牌筛选
                if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                    $handCardId = Db::name('qt_hand_card')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])->value('id');
                    if($handCardId != null){
                        $goodsWhere = true;
                    }
                    $goodsSql->where('hand_card_id',$handCardId);
                }
                //技师号筛选
                if(isset($getData['work_number']) && !empty($getData['work_number'])){
                    $engineerId = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_number'=>$getData['work_number']])->value('id');
                    $goodsSql->where('sale_id',$engineerId);
                    if($engineerId != null){
                        $goodsWhere = true;
                    }
                }
                if($goodsWhere == true){
                    $productRes = $goodsSql->select();
                }else{
                    $productRes = [];
                }
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['type'] = 'goods';
                    $productRes[$key]['project_id'] =$value['goods_id'];
                    $productRes[$key]['activity_price'] =$value['goods_price'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');
                    $productRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                    $productRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                    $productRes[$key]['old_hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                }
                $packageOriginal = array_merge($projectRes,$productRes);

                $packageProjectData = [];
                $packageGoodsData = [];
                foreach ($packageOriginal as $key=>$value){
                    if($value['type'] == 'project'){
                        if (isset($packageProjectData[$value['project_id']])) {

                            $packageProjectData[$value['project_id']]['number'] += 1;
                        }else {
                            $packageProjectData[$value['project_id']] = $value;
                            $packageProjectData[$value['project_id']]['number'] = 1;
                        }
                    }elseif($value['type'] == 'goods'){
                        if (isset($packageGoodsData[$value['goods_id']])) {

                            $packageGoodsData[$value['goods_id']]['number'] += $value['goods_num'];
                        }else {
                            $packageGoodsData[$value['goods_id']] = $value;
                            $packageGoodsData[$value['goods_id']]['number'] = $value['goods_num'];
                        }
                    }
                }
                $packageSql = Db::name('qt_data_package')
                    ->field('id,name,price')
                    ->where(['store_id'=>$this->userInfo['store_id']])
                    ->select();
                foreach ($packageSql as $key=>$value){
                    $packageSql[$key]['list'] = Db::name('qt_data_package_item')
                        ->field('id,package_id,item_id as project_id,item_type as type,number')
                        ->where(['package_id'=>$value['id']])
                        ->select();
                }
                $packageOriginalData = array_merge($packageProjectData,$packageGoodsData);
                $packageSql = CommonService::useTaoCan($packageSql,$packageOriginalData);

                $data['package'] = $packageSql;
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $data['project_new'] = CommonService::decGoodsData($projectRes,$packageSql,'project');
                $data['project_new'] = array_values($data['project_new']);
                $data['goods_new'] = CommonService::decGoodsData($productRes,$packageSql,'goods');
                $data['goods_new'] = array_values($data['goods_new']);
                $this->result('请求成功', $data, 200);
            }

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取用户房间结账支付
     */
    public function pay()
    {

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $filed_arr = [
                'viper_card_id','viper_card_money','project_order_total_id','goods_order_total_id',
                'content','activity_id','cashier_remarks','pay_content','engineer_ids','project_ids'
            ];
            foreach ($filed_arr as $key => $val){
                if (!isset($post[$val])) {
                    $post[$val] = '';
                }
            }
            $projectOrderIds = [];
            $goodsOrderIds = [];
            $roomIds = explode(',',$post['room_id']);
            if(isset($post['hand_card_ids']) && !empty($post['hand_card_ids'])){
                $handCardIds = explode(',',$post['hand_card_ids']);
            }else{
                $handCardIds = [];
            }
            $room_log = Db::name('qt_room_log')
                ->whereIn('room_id', $roomIds)
                ->order('id desc')->find();
            $room_status = Db::name('qt_room')
                ->whereIn('id', $roomIds)
                ->column('status_id');
            $room_status = implode(',',$room_status);
            try{
                Db::startTrans();
                $checkOutId = Db::name('qt_check_out')->insertGetId([
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $post['room_id'],
                    'engineer_ids' => $post['engineer_ids'],
                    'project_ids' => $post['project_ids'],
                    'order_no' => check_order_sn(),
                    'project_order' => $post['project_order_total_id'],
                    'goods_order' => $post['goods_order_total_id'],
                    'viper_card_id' => $post['viper_card_id'],
                    'viper_card_money' => $post['viper_card_money'],
                    'total_money' => $post['total_money'],
                    'payment_money' => $post['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $post['activity_id'],
                    'cashier_remarks' => $post['cashier_remarks'],
                    'pay_content' => $post['pay_content'],
                    'open_room_time' => $room_log['created_time'] ?? time(),
                    'room_status'=>$handCardIds,
                    'hand_card_id'=>$post['hand_card_ids']
                ]);
                check_out_pay_all($post['pay_content'], $checkOutId, $this->userInfo, '2');
                //会员卡结算 card_pay_type 1 会员卡余额 2 次卡 3 月卡
                if (isset($post['card_data']) && !empty($post['card_data'])) {
                    $cardData = json_decode($post['card_data'], true);
                    foreach ($cardData as $key => $value) {
                        //会员次卡结账
                        if ($value['card_pay_type'] == '2') {
                            $pay_num_card = RoomCheckOutService::payNumberCard($value, $checkOutId);
                            if (!empty($pay_num_card['code']) && $pay_num_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_num_card['msg'], '', 204);
                            }
                            $pay_card = RoomCheckOutService::payCard($value, $checkOutId,$this->userInfo);
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        } elseif ($value['card_pay_type'] == '3') {
                            //会员月卡结账
                            $pay_month_card = RoomCheckOutService::payMonthCard($value, $checkOutId);
                            if (!empty($pay_month_card['code']) && $pay_month_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_month_card['msg'], '', 204);
                            }
                            $pay_card = RoomCheckOutService::payCard($value, $checkOutId,$this->userInfo);
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        } elseif ($value['card_pay_type'] == '1') {
                            //会员卡结账
                            $pay_card = RoomCheckOutService::payCard($value, $checkOutId,$this->userInfo);
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        }
                    }
                }
                //项目计算
                $projectRes = json_decode($post['project'], true);
                $totalProjectPrice = 0;
                $projectInsert = [];
                if(!empty($projectRes)){
                    foreach ($projectRes as $key => $value) {
                        if(!isset($value['activity_price'])){
                            $value['activity_price'] = $value['payment_price'];
                        }
                        $projectInsert[$key] = [
                            'activity_id' => $post['activity_id'],
                            'link_id' => $value['project_id'],
                            'link_type' => '1',
                            'link_order_id' => $value['project_order_id'],
                            'check_out_id' => $checkOutId,
                            'receivable' => $value['payment_price'] ?? $value['price'],
                            'actual_receipt' => $value['activity_price'] ?? $value['price'],
                            'total_num' => 1,
                            'deduction_price' => $value['payment_price'] - $value['activity_price'],
                            'create_time'=>time()
                        ];
                        $totalProjectPrice += $value['payment_price'];
                        if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                            $value['is_discount'] = 0;
                        }
                        if(!empty($value['activity_price'])){
                            $payment = $value['activity_price'];
                        }else{
                            $payment =$value['payment_price'];
                        }
                        Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                            'payment_price' => $payment,
                            'is_discount' => $value['is_discount'],
                            'pay_status' => '1',
                            'pay_time' => time()
                        ]);
                        //如果有手牌减手牌金额
                        $projectOrderData = Db::name('qt_order_project')->where('id', $value['project_order_id'])->find();
                        if(!empty($projectOrderData['hand_card_id'])){
                            $handGrand = Db::name('qt_hand_grant')
                                ->where(['hand_card_id'=>$projectOrderData['hand_card_id'],'status'=>'2'])
                                ->order('id desc')
                                ->find();
                            Db::name('qt_hand_grant')->where(['id'=>$handGrand])->setDec('money',$value['price']);
                        }
                        //更新提成记录时间
                        Db::name('qt_commission_log')
                            ->where(['order_project_id' => $value['project_order_id'], 'type' => '1'])
                            ->update(['updated_time' => time(),'payment_price'=>$payment]);
                        $projectOrderIds[$key] = $value['project_order_id'];
                    }
                    //更新详情订单号
                    Db::name('qt_order_detail')->whereIn('order_project_id',$projectOrderIds)->update(['check_out_id'=>$checkOutId]);
                }
                //商品数据插入
                $totalGoodsPrice = 0;
                $goodsInsert = [];
                $goodsRes = json_decode($post['goods'], true);
                if (!empty($goodsRes)) {
                    foreach ($goodsRes as $key => $value) {
                        if(!isset($value['activity_price'])){
                            $value['activity_price'] = $value['payment_price'];
                        }
                        $goodsInsert[$key] = [
                            'activity_id' => $post['activity_id'],
                            'link_id' => $value['goods_id'],
                            'link_type' => '2',
                            'link_order_id' => $value['product_order_id'],
                            'check_out_id' => $checkOutId,
                            'receivable' => bcmul($value['payment_price'],$value['goods_num'],1)  ?? bcmul($value['goods_total_price'],$value['goods_num'],1),
                            'actual_receipt' => bcmul($value['activity_price'] ,$value['goods_num'],1) ?? bcmul($value['goods_total_price'],$value['goods_num'],1),
                            'total_num' => $value['goods_num'],
                            'deduction_price' => bcsub($value['payment_price'],$value['activity_price']),
                            'create_time'=>time()
                        ];
                        $totalGoodsPrice += intval($value['payment_price']);
                        if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                            $value['is_discount'] = 0;
                        }
                        if(!empty($value['activity_price'])){
                            $payment = $value['activity_price'];
                        }else{
                            $payment =$value['payment_price'];
                        }
                        Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                            'payment_price' => $payment * $value['goods_num'] ,
                            'is_discount' => $value['is_discount'],
                            'pay_status' => '1',
                            'pay_time'=>time()
                        ]);
                        //如果有手牌减手牌金额
                        $goodsOrderData = Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->find();
                        if(!empty($goodsOrderData['hand_card_id'])){
                            $handGrand = Db::name('qt_hand_grant')
                                ->where(['hand_card_id'=>$goodsOrderData['hand_card_id'],'status'=>'2'])
                                ->order('id desc')
                                ->find();
                            Db::name('qt_hand_grant')->where(['id'=>$handGrand])->setDec('money',$value['goods_total_price']);
                        }
                        //更新提成记录时间
                        Db::name('qt_commission_log')
                            ->where(['order_project_id' => $value['product_order_id'], 'type' => '2'])
                            ->update(['updated_time' => time(),'payment_price'=>$payment]);
                        $goodsOrderIds[$key] = $value['product_order_id'];
                    }
                    Db::name('qt_order_detail')->whereIn('order_goods_id',$goodsOrderIds)->update(['check_out_id'=>$checkOutId]);
                }
                //查询技师是否在房间内
                if(!empty($roomIds)){
                    foreach ($roomIds as $key=>$value){
                        $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $value])->find();
                        //如果技师没在房间内，更新总项目订单的状态
                        if (empty($engineerStatus)) {
                            foreach ($projectOrderIds as $k=>$v){
                                //判断房间是否还有未结账的项目子订单如果没有更新总订单
                                $checkProjectOrder = Db::name('qt_order_project')
                                    ->where([ 'pay_status' => '0'])
                                    ->where('id',$v)
                                    ->find();
                                $orderId = Db::name('qt_order_project')->where('id',$v)->value('order_id');
                                if (empty($checkProjectOrder)) {
                                    //更新项目总订单
                                    Db::name('qt_order')->where('id',$orderId)->update([
                                        'pay_status' => 2,
                                        'pay_time' => time(),
                                    ]);
                                }
                            }
                        }
                    }
                }
                //判断房间是否还有未结账的商品子订单如果没有更新总订单
                foreach ($goodsOrderIds as $key=>$value){
                    $checkPGoodsOrder = Db::name('qt_product_order_item')
                        ->where([ 'pay_status' => '0'])
                        ->where('id',$value)
                        ->find();
                    if (empty($checkPGoodsOrder)) {
                        $goodsOrder = Db::name('qt_product_order_item')
                            ->where('id',$value)
                            ->find();
                        //更新项目总订单
                        Db::name('qt_product_order')->where('id', $goodsOrder['order_id'])->update([
                            'payment_price' => $totalGoodsPrice,
                            'order_status' => 1,
                            'pay_time' => time(),
                            'pay_status' => 1
                        ]);
                    }
                }
                //插入结算子表
                $subOrderInsert = array_merge($projectInsert, $goodsInsert);
                Db::name('qt_check_out_item')->insertAll($subOrderInsert);
                if(!empty($roomIds)){
                    foreach ($roomIds as $key=>$value){
                        //判断房间是否有技师
                        $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $value])->find();
                        //如果没有，更新房间状态
                        if (empty($engineerStatus)) {
                            //自动脏房
                            if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                                Db::name('qt_room')->where('id', $value)->update(['status_id' => '5']);
                            }
                        }
                    }
                }
                if ($post['total_money'] == '0') {
                    if ($this->storeInfo['is_print_zero_order'] == '1') {
                        //调用结算打印
                        //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                    }
                } else {
                    //调用结算打印
                    //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                }
                $result = PrintService::printPcBill($checkOutId,$this->userInfo);
                //门店模式为结账自动回收
                if($this->storeInfo['type'] == '4'){
                    if(!empty($handCardIds)){
                        foreach ($handCardIds as $key=>$value){
                            $this->recoveryHandCard($value,$this->userInfo);
                        }
                    }
                }
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('结算失败，请稍后再试','',204);
            }
            $this->result('结算成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取用户房间单据
     */
    public function bill()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $where = [];
            //手牌号筛选
            if (isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])) {
                $handCardId = Db::name('qt_hand_card')->where('name', $getData['hand_card_name'])->value('id');
                $where[] = ['hand_card_id', '=', $handCardId];
            }
            //技师号筛选
            if (isset($getData['work_number']) && !empty($getData['work_number'])) {
                $engineerId = Db::name('qt_users')->where('work_number', $getData['work_number'])->value('id');
                $where[] = ['engineer_id', '=', $engineerId];
            }
            //结账筛选
            if (isset($getData['pay_status']) && !empty($getData['pay_status'])) {
                $where[] = ['pay_status', '=', $getData['pay_status']];
            }
            $roomModel = new RoomModel();
            $data = $roomModel->getProductData($getData['room_id'],$where);
            $this->result('请求成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 更换商品
     */
    public function changeGoods()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['goods_id']) || empty($getData['num']) || empty($getData['product_order_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_product_order_item')
                ->where(['id' => $getData['product_order_id']])
                ->find();
            if (empty($find)) {
                $this->result('当前商品订单不存在', '', 204);
            }
            if ($find['pay_status'] == '1') {
                $this->result('已结算商品不支持修改', '', 204);
            }
            //构建新的项目
            $newProject = Db::name('qt_goods')->field('id,name,price')->where('id', $getData['goods_id'])->find();
            $updateData = [
                'old_goods_name' => $find['goods_name'],
                'goods_name' => $newProject['name'],
                'goods_price' => $newProject['price'],
                'goods_total_price' => bcmul($newProject['price'], $getData['num'], 2),
                'goods_num' => $getData['num'],
            ];
            try {
                //更新项目订单状态
                Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update($updateData);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result('更换失败', '', 204);
            }
            $this->result('更换成功', '', 200);
        }
    }


    /**
     * 删除商品
     */
    public function delGoods()
    {

        if ($this->request->isPost()) {

            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            if ($getData['type'] == '1') {//删除项目
                $order_project_info = Db::name('qt_order_project')->where(['id' => $getData['product_order_id']])->find();
                //退手牌总金额
                HandCardM::decHandCardMoney($order_project_info['id'],$order_project_info['hand_card_id'],'1');
                if (empty($order_project_info)) {
                    $this->result('当前项目订单不存在', '', 204);
                }
                if ($order_project_info['pay_status'] == '1') {
                    $this->result('已结算项目不允许删除', '', 204);
                }
                //不是加钟的情况下判断当天是否有加钟
                if ($order_project_info['order_type'] != '5') {
                    //查找今天是否有加钟
                    $addFind = Db::name('qt_order_project')
                        ->where('order_id', $order_project_info['order_id'])
                        ->where('is_delete',2)
                        ->where(['order_type' => '5', 'engineer_id' => $order_project_info['engineer_id'],'room_id'=>$order_project_info['room_id']])
                        ->find();
                    if (!empty($addFind)) {
                        $this->result('当前技师有加钟项目，请先删除加钟项目', '', 204);
                    }

                }
                //技师在其他房间并且是上钟状态的不允许删除钟
                $engineerRes = Db::name('qt_users')->where('id', $order_project_info['engineer_id'])->value('work_status');
                $queue = Db::name('qt_order_queue')->where('user_id', $order_project_info['engineer_id'])->value('room_id');
                if ($engineerRes == '4' && $queue != $order_project_info['room_id']) {
                    $this->result('当前技师已上钟不能删除', '', 204);
                }
                //删除项目
                if (Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['is_delete'=>1])) {
                    //删除项目语音播报
                    SendVoiceMsgService::delProjectVoice($order_project_info['room_id'], $order_project_info['engineer_id'], $order_project_info['name']);
                }
                //删除项目提成
                Db::name('qt_commission_log')->where(['order_project_id'=>$order_project_info['id'],'type'=>'1'])->delete();
                //更新房间状态
                $roomQueue = Db::name('qt_order_queue')
                    ->where(['room_id'=>$order_project_info['room_id']])
                    ->where('user_id','neq',$order_project_info['engineer_id'])
                    ->find();
                //如果没有其他技师更新房间状态
                if(empty($roomQueue)){
                    Db::name('qt_room')->where('id',$order_project_info['room_id'])->update(['status_id'=>'10','retreat_time'=>time()]);
                }else{
                    Db::name('qt_room')->where('id',$order_project_info['room_id'])->update(['status_id'=>$roomQueue['status']]);
                }
                //查找当前技师是否在其他房间
                if (!empty(Db::name('qt_order_queue')->where(['room_id' => $order_project_info['room_id'], 'user_id' => $order_project_info['engineer_id']])->find())) {
                    //更改技师状态为空闲
                    if($order_project_info['order_type'] == '5'){
                        $project = Db::name('qt_project')->where(['id'=>$order_project_info['project_id']])->find();
                        //查找头钟
                        $titleOrder = Db::name('qt_order_project')
                            ->where(['engineer_id'=>$order_project_info['engineer_id'],'is_delete'=>'2'])
                            ->whereIn('status',['1','2','3'])
                            ->find();
                        //更新头钟下钟时间
                        $time = $order_project_info['end_time'] - ($project['add_block_time'] * 60);
                        Db::name('qt_order_project')->where(['id'=>$titleOrder['id']])->update(['end_time'=>$time]);
                        //更新技师排位数据
                        Db::name('qt_order_queue')->where(['user_id'=>$order_project_info['engineer_id']])->update(['end_time'=>$time]);
                        //更新加钟订单状态
                        Db::name('qt_order_project')
                            ->where('is_delete',2)
                            ->where(['id'=>$getData['product_order_id']])
                            ->update(['is_change'=>'2', 'status'=>'4','return_time'=>time()]);
                    }else{
                        //有段位的删除段位费
                        $duanweiData = Db::name('qt_duanwei')
                            ->where("FIND_IN_SET(" . $order_project_info['engineer_id'] . ",engineer_id)")
                            ->where(['project_id'=>$order_project_info['project_id']])
                            ->find();
                        if(!empty($duanweiData)){
                            //查找技师是否下了商品订单
                            $orderGoodsItem = Db::name('qt_product_order_item')
                                ->where(['goods_id'=>$duanweiData['product_id'],'room_id'=>$order_project_info['room_id'],'sale_id'=>$order_project_info['engineer_id'],'business_type'=>'5'])
                                ->find();
                            if(!empty($orderGoodsItem)){
                                \app\common\model\Duanwei::delDuanweiPrice($orderGoodsItem['id']);
                            }
                        }
                        Db::name('qt_users')->where('id', $order_project_info['engineer_id'])->update(['work_status' => '1']);
                        Db::name('qt_order_queue')->where('user_id', $order_project_info['engineer_id'])
                            ->update([
                                'room_id' => null, 'project_id' => null, 'order_project_id' => null,
                                'order_user_id' => null, 'start_time' => null, 'end_time' => null,
                                'real_time' => null, 'return_time' => time(), 'status' => '1'
                            ]);
                    }
                }
                Db::name('qt_order_detail')->where('order_project_id', $getData['product_order_id'])->where(['order_type'=>1])->update(['status'=>2]);
            }


            if ($getData['type'] == '2') {
                $product_order_info = Db::name('qt_product_order_item')->where(['id' => $getData['product_order_id']])->find();
                if (empty($product_order_info)) {
                    $this->result('当前商品订单不存在', '', 204);
                }
                if ($product_order_info['pay_status'] == '1') {
                    $this->result('已结算商品不允许删除', '', 204);
                }
                //退手牌总金额
                HandCardM::decHandCardMoney($product_order_info['id'],$product_order_info['hand_card_id'],'2');
                //写云大屏播放语音文本
                $order_item = Db::name('qt_product_order_item')
                    ->alias('oi')
                    ->field(['oi.goods_name', 'oi.goods_num', 'oi.goods_total_price', 'po.room_id', 'po.engineer_id', 'r.name as room_name',])
                    ->leftJoin('qt_product_order po', 'po.id=oi.order_id')
                    ->leftJoin('qt_room r', 'po.room_id=r.id')
                    ->where('oi.store_id', $userInfo['store_id'])
                    ->where('oi.id', $getData['product_order_id'])
                    ->where(['oi.status'=>'1'])
                    ->find();
                if (!empty($order_item)) {
                    $text = $order_item['room_name'] . '  ' . $order_item['goods_name'] . ' 退单';
                    Db::name('qt_send_voice_msg')->insert(['content' => $text, 'type' => 1,'create_time'=>time(),'voice_type'=>2]);
                }
                Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update(['status'=>'2']);
                //删除项目提成
                Db::name('qt_commission_log')->where(['order_project_id'=>$product_order_info['id'],'type'=>'2'])->delete();
                Db::name('qt_order_detail')->where('order_goods_id', $getData['product_order_id'])->where(['order_type'=>2])->update(['status'=>'2']);
            }
            $this->result('删除成功', '', 200);
        }
    }


    /**
     * 修改销售人
     */
    public function changeSale()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['sale_id']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            if ($getData['type'] == '1') {
                $find = Db::name('qt_order_project')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前项目订单不存在', '', 204);
                }
                $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['sale_id' => $getData['sale_id']]);
                //更新提出成记录
                Db::name('qt_commission_log')->where('order_project_id', $getData['product_order_id'])->update(['user_id' => $getData['sale_id']]);
            }
            if ($getData['type'] == '2') {
                $find = Db::name('qt_product_order_item')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前商品订单不存在', '', 204);
                }
                $userGroup = Db::name('qt_users')->where(['id'=>$getData['sale_id']])->value('group');
                if($userGroup == '1'){
                    $commissionUpdate = ['user_id'=>$getData['sale_id'],'cashier_id'=>0];
                }else{
                    $commissionUpdate = ['user_id'=>0,'cashier_id'=>$getData['sale_id']];
                }
                $update = Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update(['sale_id' => $getData['sale_id']]);
                //更新提出成记录
                Db::name('qt_commission_log')->where('order_project_id', $getData['product_order_id'])->update($commissionUpdate);
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('修改失败', '', 204);
        }
    }


    /**
     * 修改提成
     */
    public function changeCommission()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['type']) || empty($getData['money'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            if ($getData['type'] == '1') {
                $find = Db::name('qt_order_project')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前商品项目不存在', '', 204);
                }
                $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['commission' => $getData['money']]);
                //修改提成记录
                Db::name('qt_commission_log')
                    ->where(['type' => '1', 'order_project_id' => $getData['product_order_id']])
                    ->update(['receiver' => $getData['money']]);
            }
            if ($getData['type'] == '2') {
                $find = Db::name('qt_product_order_item')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前商品订单不存在', '', 204);
                }
                $update = Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update(['receiver' => $getData['money']]);
                //修改提成记录
                Db::name('qt_commission_log')->where(['type' => '2', 'order_project_id' => $getData['product_order_id']])->update(['commission' => $getData['money']]);
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
    }


    /**
     * 修改上钟类型
     */
    public function changeClock()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['order_type'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            $find = Db::name('qt_order_project')
                ->where(['id' => $getData['product_order_id']])
                ->find();
            if ($find['order_type'] == $getData['order_type']) {
                $this->result('更改上钟类型与原来一致', '', 204);
            }

            if (empty($find)) {
                $this->result('当前项目订单不存在', '', 204);
            }
            //加钟不能改为其他类型
            if ($find['order_type'] == '5') {
                $this->result('加钟不支持更改为其他类型', '', 204);
            }
            //其他类型不支持改为加钟
            if ($getData['order_type'] == '5') {
                $this->result('不支持更改为加钟', '', 204);
            }
            $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['order_type' => $getData['order_type']]);
            //如果是轮排改为加钟的话，并且技师为空闲状态，还原技师的顺序
            if ($find['order_type'] == '1' && $getData['order_type'] == '2') {
                $engineerStatus = Db::name('qt_users')->where('id', $find['engineer_id'])->value('work_status');
                if ($engineerStatus == '1') {
                    //技师状态为空闲时候还原技师顺序
                    $queue = Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->find();
                    Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->update(['sort' => $queue['old_sort'], 'old_sort' => $queue['sort']]);
                }
            }
            //如果是轮排改为call钟的话，并且技师为空闲状态，还原技师的顺序
            if ($find['order_type'] == '1' && $getData['order_type'] == '3') {
                $engineerStatus = Db::name('qt_users')->where('id', $find['engineer_id'])->value('work_status');
                if ($engineerStatus == '1') {
                    //技师状态为空闲时候还原技师顺序
                    $queue = Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->find();
                    Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->update(['sort' => $queue['old_sort'], 'old_sort' => $queue['sort']]);
                }
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
    }


    /**
     * 修改时间
     */
    public function changeTime()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['time']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            $find = Db::name('qt_order_project')
                ->where(['id' => $getData['product_order_id']])
                ->find();
            if ($getData['type'] == '1') {
                //提前
                $time = $find['start_time'] - ($getData['time'] * 60);
            }
            if ($getData['type'] == '2') {
                //推迟
                $time = $find['start_time'] + ($getData['time'] * 60);
            }
            $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['start_time' => $time]);
            //修改当前上钟的时间
            $orderQueue = Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->find();
            if (!empty($orderQueue['start_time']) && empty($orderQueue['end_time'])) {
                Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->update(['start_time' => $time]);
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
    }


    /**
     * 获取次卡详细内容
     */
    public function getNumberTemplate()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id']) || empty($getData['viper_card_id'])) {
                $this->result('缺少参数', '', 204);
            }
            static $couponData = [];
            $resultTemplate = [];
            $resultProject = [];
            $i = 0;
            if (!empty($getData['goods'])) {
                //处理商品抵扣
                $goodsIds = explode(',', $getData['goods']);
                //查询缓存里面是否存在
                foreach ($goodsIds as $key => $value) {
                    $goodsRes = Db::name('qt_goods')->where('id', $value)->find();
                    $resultTemplate[$key]['product_name'] = $goodsRes['name'];
                    $template = Db::name('qt_viper_number_card_template_item')
                        ->field('t.id,t.expire,t.create_time,ci.id as card_item_id,ci.total_number,ci.use_number')
                        ->alias('tt')
                        ->leftJoin('qt_viper_number_card_template t', 't.id = tt.number_card_template_id')
                        ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                        ->where(['tt.item_type'=> 'goods','ci.viper_card_id'=>$getData['viper_card_id'],'tt.item_id'=>$value,'t.viper_type_id'=>$getData['viper_type_id']])
                        ->group('t.viper_type_id')
                        ->select();
                    if (empty($template)) {
                        //无抵扣次卡
                        $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                        $resultTemplate[$key]['id'] = '';//抵扣次卡模板ID
                        $resultTemplate[$key]['name'] = '';//抵扣次卡项目合集
                        $resultTemplate[$key]['num'] = '';//抵扣次卡数量
                        $resultTemplate[$key]['expire'] = '';//抵扣次卡有效期
                        $resultTemplate[$key]['price'] = $goodsRes['price'];
                        $resultTemplate[$key]['card_item_id'] = '';//购买次卡的ID
                    } else {
                        //有抵扣次卡
                        foreach ($template as $k => $v) {
                            $resultTemplate[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_number_card_template_item')->where('number_card_template_id', $v['id'])->find();
                            //次卡包含的商品
                            $nameData = Db::name('qt_viper_number_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_goods g', 'g.id = item.item_id')
                                ->where('item.number_card_template_id', $v['id'])
                                ->where('item.item_type', 'goods')
                                ->column('g.name');
                            $resultTemplate[$key]['name'] = implode(',', $nameData);
                            $resultTemplate[$key]['num'] = $v['total_number'];
                            $resultTemplate[$key]['expire'] = ($data['expire'] * 86400) + $v['create_time'];
                            $resultTemplate[$key]['price'] = $goodsRes['price'];
                            $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                            $resultTemplate[$key]['card_item_id'] = $v['card_item_id'];
                            $couponData[$i]['id'] = $v['id'];
                            $couponData[$i]['name'] = implode(',', $nameData);
                            $couponData[$i]['expire'] = ($data['expire'] * 86400) + $v['create_time'];
                            $couponData[$i]['num'] = $v['total_number'] - $v['use_number'];
                            $couponData[$i]['card_item_id'] = $v['card_item_id'];
                            $i++;
                        }
                    }
                }
            }
            if (!empty($getData['project'])) {
                //处理项目抵扣
                $projectIds = explode(',', $getData['project']);
                foreach ($projectIds as $key => $value) {
                    $projectRes = Db::name('qt_project')->where('id', $value)->find();
                    $resultProject[$key]['product_name'] = $projectRes['name'];
                    $template = Db::name('qt_viper_number_card_template_item')
                        ->field('t.id,t.expire,t.create_time,ci.id as card_item_id,ci.total_number,ci.use_number')
                        ->alias('tt')
                        ->leftJoin('qt_viper_number_card_template t', 't.id = tt.number_card_template_id')
                        ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                        ->where('tt.item_type', 'project')
                        ->where('tt.item_id', $value)
                        ->where('t.viper_type_id', $getData['viper_type_id'])
                        ->group('t.viper_type_id')
                        ->select();
                    if (empty($template)) {
                        //无抵扣次卡
                        $resultProject[$key]['product_id'] = 'project-' . $value;//项目ID
                        $resultProject[$key]['id'] = '';//抵扣次卡模板ID
                        $resultProject[$key]['name'] = '';//抵扣次卡项目合集
                        $resultProject[$key]['num'] = '';//抵扣次卡数量
                        $resultProject[$key]['expire'] = '';//抵扣次卡有效期
                        $resultProject[$key]['price'] = $projectRes['price'];//价格
                        $resultProject[$key]['card_item_id'] = '';//购买次卡的ID
                    } else {
                        //有抵扣次卡
                        foreach ($template as $k => $v) {
                            $resultProject[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_number_card_template_item')->where('number_card_template_id', $v['id'])->find();
                            //次卡包含的项目
                            $dataName = Db::name('qt_viper_number_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_project p', 'p.id = item.item_id')
                                ->where('item.number_card_template_id', $v['id'])
                                ->where('item.item_type', 'project')
                                ->column('p.name');
                            $resultProject[$key]['product_id'] = 'project-' . $value;//项目ID
                            $resultProject[$key]['name'] = implode(',', $dataName);
                            $resultProject[$key]['num'] = '1';
                            $resultProject[$key]['expire'] = ($data['expire'] * 86400) + $data['create_time'];
                            $resultProject[$key]['price'] = $projectRes['price'];
                            $resultProject[$key]['card_item_id'] = $v['card_item_id'];
                            $couponData[$i]['id'] = $v['id'];
                            $couponData[$i]['name'] = implode(',', $dataName);
                            $couponData[$i]['expire'] = ($data['expire'] * 86400) + $data['create_time'];
                            $couponData[$i]['num'] = $v['total_number']- $v['use_number'];
                            $couponData[$i]['card_item_id'] = $v['card_item_id'];
                            $i++;
                        }
                    }
                }
            }
            $result = array_merge($resultTemplate, $resultProject);
            $couponData = unique_2d_array_by_key($couponData, 'name');
            $newData ['coupon'] = $couponData;
            $newData ['result'] = $result;
            $this->result('查询成功', $newData, 200);
        }
    }


    /**
     * 获取月卡详细内容
     */
    public function getMonthTemplate()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id']) || empty($getData['viper_card_id'])) {
                $this->result('缺少参数', '', 204);
            }
            static $couponData = [];
            $i = 0;
            $resultTemplate = [];
            if (!empty($getData['goods'])) {
                //处理商品抵扣
                $goodsIds = explode(',', $getData['goods']);
                foreach ($goodsIds as $key => $value) {
                    $goodsRes = Db::name('qt_goods')->where('id', $value)->find();
                    $resultTemplate[$key]['product_name'] = $goodsRes['name'];
                    $template = Db::name('qt_viper_month_card_template_item')
                        ->field('t.id,t.expire,t.create_time,ci.id as card_item_id')
                        ->alias('tt')
                        ->leftJoin('qt_viper_month_card_template t', 't.id = tt.month_template_id')
                        ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                        ->where(['tt.item_type'=> 'goods','tt.item_id'=>$value,'t.viper_type_id'=>$getData['viper_type_id']])
                        ->group('t.viper_type_id')
                        ->select();
                    if (empty($template)) {
                        //无抵扣月卡
                        $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                        $resultTemplate[$key]['id'] = '';//抵扣次卡模板ID
                        $resultTemplate[$key]['name'] = '';//抵扣次卡项目合集
                        $resultTemplate[$key]['num'] = '';//抵扣次卡数量
                        $resultTemplate[$key]['expire'] = '';//抵扣次卡有效期
                        $resultTemplate[$key]['price'] = $goodsRes['price'];
                        $resultTemplate[$key]['card_item_id'] = '';
                    } else {
                        //有抵扣月卡
                        foreach ($template as $k => $v) {
                            $resultTemplate[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_month_card_template_item')->where('month_template_id', $v['id'])->find();
                            //月卡包含的商品
                            $nameData = Db::name('qt_viper_month_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_goods g', 'g.id = item.item_id')
                                ->where('item.number_card_template_id', $v['id'])
                                ->where('item.item_type', 'goods')
                                ->column('g.name');
                            $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                            $resultTemplate[$key]['name'] = implode(',', $nameData);
                            $resultTemplate[$key]['num'] = '1';
                            $resultTemplate[$key]['expire'] = $v['expire'];
                            $resultTemplate[$key]['price'] = $goodsRes['price'];
                            $resultTemplate[$key]['card_item_id'] = $v['card_item_id'];
                            $couponData[$i]['name'] = implode(',', $nameData);
                            $couponData[$i]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                            $couponData[$i]['num'] = '1';
                            $i++;

                        }
                    }
                }
            }
            //处理项目抵扣
            $projectIds = explode(',', $getData['project']);
            foreach ($projectIds as $key => $value) {
                $projectRes = Db::name('qt_project')->where('id', $value)->find();
                $resultProject[$key]['product_name'] = $projectRes['name'];
                $template = Db::name('qt_viper_month_card_template_item')
                    ->field('t.id,t.expire,t.create_time,ci.id as card_item_id')
                    ->alias('tt')
                    ->leftJoin('qt_viper_month_card_template t', 't.id = tt.month_template_id')
                    ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                    ->where('tt.item_type', 'project')
                    ->where('tt.item_id', $value)
                    ->where('t.viper_type_id', $getData['viper_type_id'])
                    ->group('t.viper_type_id')
                    ->select();
                if (empty($template)) {
                    //无抵扣次卡
                    $resultProject[$key]['product_id'] = 'project-' . $value;//商品ID
                    $resultProject[$key]['id'] = '';//抵扣次卡模板ID
                    $resultProject[$key]['name'] = '';//抵扣次卡项目合集
                    $resultProject[$key]['num'] = '';//抵扣次卡数量
                    $resultProject[$key]['expire'] = '';//抵扣次卡有效期
                    $resultProject[$key]['price'] = $projectRes['price'];//价格
                    $resultProject[$key]['card_item_id'] = '';//次卡ID
                } else {
                    //有抵扣次卡
                    foreach ($template as $k => $v) {
                        $resultProject[$key]['id'] = $v['id'];//抵扣次卡模板ID
                        //月卡包含的项目
                        $dataName = Db::name('qt_viper_month_card_template_item')
                            ->alias('item')
                            ->leftJoin('qt_project p', 'p.id = item.item_id')
                            ->where('item.month_template_id', $v['id'])
                            ->where('item.item_type', 'project')
                            ->column('p.name');
                        $resultProject[$key]['product_id'] = 'project-' . $value;//项目ID
                        $resultProject[$key]['name'] = implode(',', $dataName);
                        $resultProject[$key]['num'] = '1';
                        $resultProject[$key]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                        $resultProject[$key]['price'] = $projectRes['price'];
                        $resultProject[$key]['card_item_id'] = $v['card_item_id'];//月卡ID
                        $couponData[$i]['name'] = implode(',', $dataName);
                        $couponData[$i]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                        $couponData[$i]['num'] = '1';
                        $i++;
                    }
                }
            }
            $result = array_merge($resultTemplate, $resultProject);
            $couponData = unique_2d_array_by_key($couponData, 'name');
            $newData ['coupon'] = $couponData;
            $newData ['result'] = $result;
            $this->result('查询成功', $newData, 200);
        }
    }

    /**
     * 验证会员卡
     * @param $type [类型] [1密码，2验证码]
     * @param $code [密码或者验证码]
     * @param $cardId [会员卡ID]
     */
    public function checkPass($passwd, $code, $cardId)
    {
        $cardRes = Db::name('qt_viper_card')->field('id,passwd')->where('id', $cardId)->find();
        if (!empty($passwd)) {
            $newPass = pwd($code, $cardRes['salt']);
            if ($newPass != $cardRes['passwd']) {
                $this->result('密码错误', '', 204);
            }
        } elseif (!empty($code)) {
            $sms = new Smscm();
            $result = $sms->check_smscode($cardRes['mobile'], $code, '3');
            if ($result['code'] != '200') {
                $this->result('验证码错误', '', 204);
            }
        }
    }


    /**
     * 获取会员卡支付比例
     */
    public function viperCardDiscount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_viper_type')->field('id,amount_percentage,give_amount_percentage')->where('id', $getData['viper_type_id'])->find();
            $this->result('查询成功', $data, 200);
        }
    }


    /**
     * 获取房间项目
     */
    public function project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            $project = Db::name('qt_order')->alias('o')
                ->field('o.id,r.name as room_name')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->where(['o.room_id' => $getData['room_id'], 'o.pay_status' => '1'])
                ->order('o.id desc')
                ->find();
            $projectRes = Db::name('qt_order_project')->alias('o')
                ->field('o.id as project_order_id,o.name as project_name,o.order_type,
                o.created_time,o.price,o.payment_price,o.engineer_id,o.project_id,o.status,o.start_time,
                o.real_end_time,o.created_order_id,h.name as hand_card_name')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                ->where('o.order_id', $project['id'])
                ->whereNotNull('o.engineer_id')
                ->where(['o.is_change'=>'1','o.is_delete'=>'2'])
                ->select();
            foreach ($projectRes as $key => $value) {
                $projectRes[$key]['order_id'] = $project['id'];
                $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                $projectRes[$key]['room_name'] = $project['room_name'];
                $projectRes[$key]['hand_card_name'] = $value['hand_card_name'];
                $projectRes[$key]['create_name'] = Db::name('qt_users')->where('id', $value['created_order_id'])->value('real_name');
            }
            $this->result('查询成功', $projectRes, 200);
        }
    }


    /**
     * 计算折扣
     */
    public function discount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['active_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $result  = Discount::getDiscount($getData);
            $this->result($result['msg'], $result['data'], $result['code']);
        }
    }


    /**
     * 计算会员价格
     */
    public function vip_discount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $result  = Discount::getVipDiscount($getData);
            $this->result($result['msg'], $result['data'], $result['code']);
        }
    }


    /**
     * 订单挂账
     */
    public function credit()
    {

        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $map = [];
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            if (empty($getData['viper_card_id'])) {
                $getData['viper_card_id'] = '';
            }
            if (empty($getData['viper_card_money'])) {
                $getData['viper_card_money'] = '';
            }
            if (!empty($getData['project_order_total_id'])) {
                $map[] = ['project_order', '=', $getData['project_order_total_id']];
            }
            if (!empty($getData['goods_order_total_id'])) {

                $map[] = ['goods_order', '=', $getData['goods_order_total_id']];
            }
            //备注默认为空
            if (!isset($getData['content']) || empty($getData['content'])) {
                $getData['content'] = '';
            }
            if (!isset($getData['activity_id']) || empty($getData['activity_id'])) {
                $getData['activity_id'] = '';
            }
            if (!isset($getData['cashier_remarks']) || empty($getData['cashier_remarks'])) {
                $getData['cashier_remarks'] = '';
            }
            if (!isset($getData['pay_content']) || empty($getData['pay_content'])) {
                $getData['pay_content'] = '';
            }
            if (!isset($getData['engineer_ids']) || empty($getData['engineer_ids'])) {
                $getData['engineer_ids'] = '';
            }
            if (!isset($getData['project_ids']) || empty($getData['project_ids'])) {
                $getData['project_ids'] = '';
            }
            $find = Db::name('qt_check_out')->where($map)->where('is_revoke', '2')->find();
            if (empty($find)) {
                //构建主结算订单
                $checkOutInsert = [
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $getData['room_id'],
                    'engineer_ids' => $getData['engineer_ids'],
                    'project_ids' => $getData['project_ids'],
                    'order_no' => check_order_sn(),
                    'project_order' => $getData['project_order_total_id'],
                    'goods_order' => $getData['goods_order_total_id'],
                    'viper_card_id' => $getData['viper_card_id'],
                    'viper_card_money' => $getData['viper_card_money'],
                    'total_money' => $getData['total_money'],
                    'payment_money' => $getData['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $getData['activity_id'],
                    'cashier_remarks' => $getData['cashier_remarks'],
                    'pay_content' => $getData['pay_content'],
                    'order_type' => '2',
                ];
                $checkOutId = Db::name('qt_check_out')->insertGetId($checkOutInsert);
            } else {
                $checkOutId = $find['id'];
            }
            $totalProjectPrice = 0;
            if($getData['project'] != ''){
                //项目计算
                $projectRes = json_decode($getData['project'], true);
                $projectInsert = [];
                foreach ($projectRes as $key => $value) {
                    $projectInsert[$key] = [
                        'activity_id' => $getData['activity_id'],
                        'link_id' => $value['project_id'],
                        'link_order_id' => $value['project_order_id'],
                        'link_type' => '1',
                        'check_out_id' => $checkOutId,
                        'receivable' => $value['payment_price'] ?? $value['price'],
                        'actual_receipt' => $value['activity_price'] ?? $value['price'],
                    ];
                    $totalProjectPrice += $value['payment_price'];
                    if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                        $value['is_discount'] = 0;
                    }
                    Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                        'payment_price' => $value['payment_price'],
                        'is_discount' => $value['is_discount'],
                        'pay_status' => '2',
                        'pay_time' => time()
                    ]);
                }
                Db::name('qt_check_out_item')->insertAll($projectInsert);
            }

            //商品数据插入
            $totalGoodsPrice = 0;
            if($getData['goods'] != ''){
                $goodsRes = json_decode($getData['goods'], true);
                if (empty($goodsRes)) {
                    $goodsInsert = [];
                }
                foreach ($goodsRes as $key => $value) {
                    $goodsInsert[$key] = [
                        'activity_id' => $getData['activity_id'],
                        'link_id' => $value['goods_id'],
                        'link_type' => '2',
                        'link_order_id' => $value['product_order_id'],
                        'check_out_id' => $checkOutId,
                        'receivable' => $value['payment_price'] ?? $value['goods_total_price'],
                        'actual_receipt' => $value['activity_price'] ?? $value['goods_total_price'],
                    ];
                    $totalGoodsPrice += $value['payment_price'];
                    if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                        $value['is_discount'] = 0;
                    }
                    Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                        'payment_price' => $value['payment_price'],
                        'is_discount' => $value['is_discount'],
                        'pay_status' => '2'
                    ]);
                }
                Db::name('qt_check_out_item')->insertAll($goodsInsert);
            }
            //查询技师是否在房间内
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //判断房间是否还有未结账的项目子订单如果没有更新总订单
            $checkProjectOrder = Db::name('qt_order_project')->where(['order_id' => $getData['project_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkProjectOrder)) {
                //如果技师没在房间内，更新总项目订单的状态
                if (empty($engineerStatus)) {
                    //更新项目总订单
                    Db::name('qt_order')->where('id', $getData['project_order_total_id'])->update([
                        'payment_price' => $totalProjectPrice,
                        'pay_status' => 2,
                        'pay_time' => time(),
                    ]);
                }
            }
            //判断房间是否还有未结账的商品子订单如果没有更新总订单
            $checkPGoodsOrder = Db::name('qt_product_order_item')->where(['order_id' => $getData['goods_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkPGoodsOrder)) {
                //更新项目总订单
                Db::name('qt_product_order')->where('id', $getData['goods_order_total_id'])->update([
                    'payment_price' => $totalGoodsPrice,
                    'order_status' => 1,
                    'pay_time' => time(),
                    'pay_status' => 1
                ]);
            }
            //判断房间是否有技师
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //如果没有，更新房间状态
            if (empty($engineerStatus)) {
                //自动脏房
                if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                    Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '5']);
                }
            }
            //调用结算打印
            //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
            //插入挂账信息
            $insertCheng = [];
            if (empty($getData['charge_id'])) {
                if(empty($getData['company_id'])){
                    $getData['company_id'] = null;
                }
                $insertCheng = [
                    'store_id' => $this->userInfo['store_id'],
                    'user_id' => $this->userInfo['id'],
                    'company_id' => $getData['company_id'],
                    'name' => $getData['name'],
                    'phone' => $getData['phone'],
                    'total_price' => $getData['total_money'],
                    'payment_price' => 0,
                    'content' => '',
                    'create_time' => time(),
                    'update_time' => time(),
                ];

            }
            if(!empty($insertCheng)){
                //插入挂账订单
                $chargeID = Db::name('qt_charge')->insertGetId($insertCheng);
            }
            try {
                Db::startTrans();
                if (!empty($getData['charge_id'])) {
                    $insertItemData = [
                        'user_id' => $this->userInfo['id'],
                        'charge_id' => $getData['charge_id'],
                        'check_out_id' => $checkOutId,
                        'content' => $getData['charge_content'],
                        'create_time' => time(),
                        'store_id' => $this->userInfo['store_id'],
                    ];
                    //增加金额
                    Db::name('qt_charge')->where('id', $getData['charge_id'])->setInc('total_price', $getData['total_money']);
                    //更新最后挂账时间
                    Db::name('qt_charge')->where('id', $getData['charge_id'])->update(['update_time'=>time()]);
                } else {
                    $insertItemData = [
                        'user_id' => $this->userInfo['id'],
                        'charge_id' => $chargeID,
                        'check_out_id' => $checkOutId,
                        'content' => $getData['charge_content'],
                        'create_time' => time(),
                        'store_id' => $this->userInfo['store_id'],
                    ];
                }
                //更新订单状态
                Db::name('qt_charge_item')->insert($insertItemData);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('挂账失败', '', 204);
            }
            $this->result('挂账成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 用户挂账结账列表
     */
    public function credit_bill()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['check_out_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $checkOutIds = explode(',',$getData['check_out_id']);
            $checkOutData = Db::name('qt_check_out')->field('id,project_order,goods_order')->whereIn('id',$checkOutIds)->select();
            $projectOrder = [];//项目订单ID合集
            $goodsOrder = [];//商品订单ID合集
            $roomId = '';
            $roomProjectId = [];
            $roomGoodsId = [];
            foreach ($checkOutData as $key=>$value){
                $projectOrder[$key] = $value['project_order'];
                $goodsOrder[$key] = $value['goods_order'];
            }
            $projectOrderIds = Db::name('qt_check_out_item')->whereIn('check_out_id',$checkOutIds)->where(['link_type'=>'1'])->column('link_order_id');
            $projectRes = Db::name('qt_order_project')
                ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,order_id,engineer_id,room_id,hand_card_id')
                ->whereIn('id', $projectOrderIds)
                ->select();
            foreach ($projectRes as $key => $value) {
                $projectRes[$key]['type'] = 'project';
                $projectRes[$key]['activity_price'] = $value['price'];
                $projectRes[$key]['order_id'] = $value['order_id'];
                $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                $roomProjectId[$key] = $value['room_id'];
            }
            //商品
            $goods = Db::name('qt_product_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name,engineer_id')
                ->alias('o')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                ->whereIn('o.id',$goodsOrder)
                ->column('o.id');
            $productRes = Db::name('qt_product_order_item')
                ->field('id as product_order_id,room_id,goods_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,business_type,order_id')
                ->whereIn('order_id',$goods)
                ->where('pay_status', '2')
                ->where(['status'=>'1'])
                ->select();
            foreach ($productRes as $key => $value) {
                $productRes[$key]['type'] = 'goods';
                $productRes[$key]['project_id'] =$value['goods_id'];
                $productRes[$key]['activity_price'] =$value['goods_price'];
                $productRes[$key]['engineer_name'] = '';
                $productRes[$key]['room_name'] = Db::name('qt_room')->where(['id'=>$value['room_id']])->value('name');
                $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                $roomGoodsId[$key] = $value['room_id'];
            }

            $packageOriginal = array_merge($projectRes,$productRes);
            $packageProjectData = [];
            $packageGoodsData = [];
            foreach ($packageOriginal as $key=>$value){
                if($value['type'] == 'project'){
                    if (isset($packageProjectData[$value['project_id']])) {

                        $packageProjectData[$value['project_id']]['number'] += 1;
                    }else {
                        $packageProjectData[$value['project_id']] = $value;
                        $packageProjectData[$value['project_id']]['number'] = 1;
                    }
                }elseif($value['type'] == 'goods'){
                    if (isset($packageGoodsData[$value['goods_id']])) {

                        $packageGoodsData[$value['goods_id']]['number'] += $value['goods_num'];
                    }else {
                        $packageGoodsData[$value['goods_id']] = $value;
                        $packageGoodsData[$value['goods_id']]['number'] = $value['goods_num'];
                    }
                }
            }
            $packageSql = Db::name('qt_data_package')
                ->field('id,name,price')
                ->where(['store_id'=>$this->userInfo['store_id']])
                ->select();
            foreach ($packageSql as $key=>$value){
                $packageSql[$key]['list'] = Db::name('qt_data_package_item')
                    ->field('id,package_id,item_id as project_id,item_type as type,number')
                    ->where(['package_id'=>$value['id']])
                    ->select();
            }
            $packageOriginalData = array_merge($packageProjectData,$packageGoodsData);
            $packageSql = CommonService::useTaoCan($packageSql,$packageOriginalData);

            $roomId = array_merge($roomProjectId,$roomGoodsId);
            if(!empty($roomId)){
                $roomId = array_unique($roomId);
                $roomId = implode(',',$roomId);
            }

            $data['package'] = $packageSql;
            $data['project'] = $projectRes;
            $data['goods'] = $productRes;
            $data['project_new'] = CommonService::decGoodsData($projectRes,$packageSql,'project');
            $data['project_new'] = array_values($data['project_new']);
            $data['goods_new'] = CommonService::decGoodsData($productRes,$packageSql,'goods');
            $data['goods_new'] = array_values($data['goods_new']);
            $data['room_id'] = $roomId;
            $this->result('请求成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 挂账结账支付
     */
    public function credit_pay()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            //备注默认为空
            if (!isset($getData['content']) || empty($getData['content'])) {
                $getData['content'] = '';
            }
            if (!isset($getData['activity_id']) || empty($getData['activity_id'])) {
                $getData['activity_id'] = '';
            }
            if (!isset($getData['cashier_remarks']) || empty($getData['cashier_remarks'])) {
                $getData['cashier_remarks'] = '';
            }
            if (!isset($getData['pay_content']) || empty($getData['pay_content'])) {
                $getData['pay_content'] = '';
            }
            if (!isset($getData['engineer_ids']) || empty($getData['engineer_ids'])) {
                $getData['engineer_ids'] = '';
            }
            if (!isset($getData['project_ids']) || empty($getData['project_ids'])) {
                $getData['project_ids'] = '';
            }
            //结账单ID
            $checkOutIds = explode(',',$getData['check_out_id']);
            foreach ($checkOutIds as $key=>$value){
                check_out_pay_all($getData['pay_content'], $value, $this->userInfo, '2','0','1');
                //会员卡结算 card_pay_type 1 会员卡余额 2 次卡 3 月卡
                if (isset($getData['card_data']) && !empty($getData['card_data'])) {
                    $cardData = json_decode($getData['card_data'], true);
                    foreach ($cardData as $k => $v) {
                        //会员次卡结账
                        if ($v['card_pay_type'] == '2') {
                            $pay_number_card = RoomCheckOutService::payNumberCard($v, $value);
                            if (!empty($pay_number_card['code']) && $pay_number_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_number_card['msg'], '', 204);
                            }
                            $pay_card = RoomCheckOutService::payCard($v, $value,$this->userInfo,'1');
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        } elseif ($value['card_pay_type'] == '3') {
                            //会员月卡结账
                            $pay_month_card = RoomCheckOutService::payMonthCard($v, $value);
                            if (!empty($pay_month_card['code']) && $pay_month_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_month_card['msg'], '', 204);
                            }
                            $pay_card = RoomCheckOutService::payCard($v, $value,$this->userInfo,'1');
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        } elseif ($value['card_pay_type'] == '1') {
                            //会员卡结账
                            $pay_card = RoomCheckOutService::payCard($v, $value,$this->userInfo,'1');
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        }
                    }
                }
                $checkOutData = Db::name('qt_check_out')->where(['id'=>$value])->find();
                Db::name('qt_check_out')->where(['id'=>$value])->update(['order_type'=>'1','cashier_time'=>time(),'payment_money'=>$checkOutData['total_money']]);
                //删除挂账订单
                $changeId = Db::name('qt_charge_item')->where(['check_out_id'=>$value])->value('charge_id');
                $changeMoney = Db::name('qt_check_out')->where(['id'=>$value])->value('total_money');
                Db::name('qt_charge_item')->where(['check_out_id'=>$value])->delete();
                //增加实际支付金额
                Db::name('qt_charge')->where(['id'=>$changeId])->setInc('payment_price',$changeMoney);
                //增加实际支付金额
                Db::name('qt_charge')->where(['id'=>$changeId])->setDec('total_price',$changeMoney);
            }
            if ($getData['total_money'] == '0') {
                if ($this->storeInfo['is_print_zero_order'] == '1') {
                    //调用结算打印
                    FeiEPrintService::printPhoneBills($checkOutIds,$this->userInfo);
                }
            } else {
                //调用结算打印
                //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
            }
            $result = PrintService::printPcBills($checkOutIds,$this->userInfo);
            $this->result('结算成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 首页右键房间账单详情
     */
    public function bail_detail()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $result['marge_data'] = [];
            $roomData = \app\common\model\Room::get($getData['room_id']);
            if(!empty($roomData['marge'])){
                $roomIds = explode(',',$roomData['marge']);
                $result['marge_data'] = Db::name('qt_room')->whereIn('id',$roomIds)->column('name');
            }
            $roomModel = new RoomModel();
            $result['product_data'] = $roomModel->getProductData($getData['room_id']);
            $result['appointment_data'] = $roomModel->getAppointment($getData['room_id']);
            $result['open_data'] = $roomModel->getOpen($getData['room_id']);
            //查询项目的结账单
            $projectOrder = Db::name('qt_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name')
                ->alias('o')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                ->where(['room_id' => $getData['room_id'], 'pay_status' => '1'])
                ->order('o.id desc')
                ->find();
            $chekOut = Db::name('qt_check_out')
                ->field('c.id,c.mobile,c.name,c.amount')
                ->alias('out')
                ->leftJoin('qt_check_out_pay pay','pay.check_out_id = out.id')
                ->leftJoin('qt_viper_card c','c.id = pay.viper_card_id')
                ->where(['out.project_order'=>$projectOrder['id'],'pay.pay_id'=>'6'])
                ->select();
            $result['viper_card_data'] = $chekOut;
            $this->result('请求成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 回收手牌
     */
    public function  recoveryHandCard($handCardId,$userInfo)
    {
        //查询是否有未结账的商品和项目
        $projectOrder = Db::name('qt_order_project')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0'])->find();
        $goodsOrder = Db::name('qt_product_order_item')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0'])->find();
        if($projectOrder == null && $goodsOrder == null){
            $update = [
                'status'=>'3',
                'update_time'=>time(),
                'recovery_id'=>$userInfo['id']
            ];
            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_hand_card')->where(['id'=>$handCardId])->update(['status'=>'1']);
                Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId])->order('id desc')->update($update);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
            }
        }
    }

    /**
     * 房间单据更换手牌
     */
    public function changeHandCard(){

        if ($this->request->isPost()) {
            $post = $this->request->post();

            if (empty($post['hand_card_name']) || empty($post['order_id']) || empty($post['type'])) {
                $this->result('缺少参数', '', 204);
            }
            $order_data_price = 0;
            if($post['type'] == '1'){//1项目 2商品
                $order_data = Db::name('qt_order_project')->where(['id'=>$post['order_id']])->find();
                $order_data_price = $order_data['price'];
            }else{
                $order_data = Db::name('qt_product_order_item')->where(['id'=>$post['order_id']])->find();
                $order_data_price = $order_data['goods_price'];
            }

            if (empty($order_data)) $this->result('单据数据异常', '', 204);

            $new_hand_card_data = Db::name('qt_hand_card')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('name', $post['hand_card_name'])
                ->find();
            if (empty($new_hand_card_data)) $this->result('没有找到新手牌'.$post['hand_card_name'] .'号','',204);


            //检测最大消费金额
            $checkMoney = HandCard::checkMaxMoney($new_hand_card_data['id'],$order_data_price);
            if($checkMoney == false){
                $this->result('手牌超出最大消费', '', 204);
            }
            //检测停牌
            $checkStatus = HandCard::checkStatus($new_hand_card_data['id']);
            if($checkStatus == false) $this->result('新手牌未发放', '', 204);

            //判断新手牌是否发放,如果手牌使用了不能发放
            $new_hand_grant_data = Db::name('qt_hand_grant')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('hand_card_id', $new_hand_card_data['id'])
                ->where('status',2)
                ->find();
            if (empty($new_hand_grant_data)) $this->result('新手牌未发放','',204);

            //更新新房间信息
            Db::startTrans();
            try {

                //更新项目
                if($post['type'] == '1'){//1项目 2商品
                    Db::name('qt_order_project')
                        ->where(['id' => $post['order_id']])
                        ->update(['hand_card_id' => $new_hand_card_data['id'], 'old_card_id' => $order_data['hand_card_id']]);

                    //老手牌減少金额
                    HandCardM::decHandCardMoney($post['order_id'],$order_data['hand_card_id'],'1');
                    //新手牌增加金额
                    HandCardM::incHandCardMoney($post['order_id'],$new_hand_card_data['id'],'1');

                } else {    //更新商品
                    Db::name('qt_product_order_item')
                        ->where(['id' =>$post['order_id']])
                        ->update(['hand_card_id' => $new_hand_card_data['id'], 'old_card_id' => $order_data['hand_card_id']]);

                    //老手牌減少金额
                    HandCardM::decHandCardMoney($post['order_id'],$order_data['hand_card_id'],'2');
                    //新手牌增加金额
                    HandCardM::incHandCardMoney($post['order_id'],$new_hand_card_data['id'],'2');
                }

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('转手牌失败', '', 204);
            }

            $this->result('转手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);

    }


    /**
     * 查询套餐费用
     */
    public static function package($orderProjectData,$goodsOrderData){
        //处理项目
        $key = array_column($orderProjectData,'project_id');
        array_multisort($key,SORT_ASC,$orderProjectData);
        $projectOrg = [];
        foreach ($orderProjectData as $key=>$value){
            $projectOrg[$key]= $value['project_id'].'-project-'.'1';
        }
        $project = array_unique($projectOrg);
        $project = array_values($project);
        $cha = array_diff_assoc($projectOrg,$project);
        //处理商品
        $key = array_column($goodsOrderData,'goods_id');
        array_multisort($key,SORT_ASC,$goodsOrderData);
        $goods = [];
        foreach ($goodsOrderData as $key=>$value){
            $goods[$key]= $value['goods_id'].'-goods-'.$value['goods_num'];
        }
        $goods = array_unique($goods);
        $goods = array_values($goods);
        $stringData = array_merge($project,$goods);
        $string = implode(',',$stringData);
        return $string;
    }



}
